package com.example.home.view

import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.app.RouterPath
import com.example.common.mvi.BaseMviFragment
import com.example.home.R
import com.example.home.adapter.HomePageAdapter
import com.example.home.databinding.FragmentHomeBinding
import com.example.home.entity.SimpleTypeEntity
import com.example.home.intent.HomeViewIntent
import com.example.home.state.HomeUiState
import com.example.home.vm.HomeViewModel
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect

@AndroidEntryPoint
@Route(path = RouterPath.PATH_HOME_PAGE)
class HomeFragment : BaseMviFragment<FragmentHomeBinding>() {
    private val mViewModel: HomeViewModel by activityViewModels()
    private val mTabList = mutableListOf<SimpleTypeEntity>()
    private val mListFragment = mutableListOf<HomeListFragment>()
    private lateinit var homePageAdapter: HomePageAdapter
    private val searchHotWords= listOf("热门视频","搞笑视频","广场舞视频")
    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun initViews() {
        //初始化搜索框
        mDataBinding.tvbSearch.apply {
            setDatas(searchHotWords)
            setItemOnClickListener{data,_->
                //跳转到搜索页面
                ARouter.getInstance().build(RouterPath.PATH_SEARCH_PAGE).withString("keyword",data).navigation()
            }
        }
        homePageAdapter= HomePageAdapter(mListFragment,this.childFragmentManager,lifecycle)
        mDataBinding.vp2Home.adapter=homePageAdapter
        mDataBinding.vp2Home.offscreenPageLimit=1
        //关联
        TabLayoutMediator(mDataBinding.tabTypeLayout, mDataBinding.vp2Home) { tab, position ->
            tab.text = mTabList[position].typename
        }.attach()

        //注册页面切换事件
        mDataBinding.vp2Home.registerOnPageChangeCallback(object :OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (mListFragment[position].isAdded){
                    mListFragment[position].lazyLoadData()
                }else{
                    mDataBinding.vp2Home.postDelayed({
                        mListFragment[position].lazyLoadData()
                    },300)
                }
            }
        })

    }

    /**
     * 发起意图
     */
    override suspend fun sendViewIntent() {
        mViewModel.channel.send(HomeViewIntent.LoadVideType)
    }

    /**
     * 收集UI状态
     */
    override suspend fun collectUIState() {
        super.collectUIState()
        mViewModel.uiSharedFlow.collect{
            when(it){
                is HomeUiState.LoadSimpleTypeSuccess->{initSimpleTypeLayout(it.list)}
                is HomeUiState.LoadSimpleTypeFail->{ToastUtils.showLong(it.msg)}
                else->{}
            }
        }
    }

    private fun initSimpleTypeLayout(list:List<SimpleTypeEntity>) {
        if (list.isNotEmpty()){
            //添加分类集合
            mTabList.add(SimpleTypeEntity("",0,-1,0,"","推荐"))
            mListFragment.add(HomeListFragment.newInstance("",-1))
            //其他分类
            list.forEach {
                mTabList.add(it)
                mListFragment.add(HomeListFragment.newInstance(it.channelid,it.id))
            }
            mTabList.forEach{
                mDataBinding.tabTypeLayout.addTab(mDataBinding.tabTypeLayout.newTab().setText(it.typename))
            }
            homePageAdapter.notifyDataSetChanged()
        }
    }


}